package org.redis.cluster.admin;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.env.Environment;

@ImportResource("classpath*:main.xml")
@SpringBootApplication
public class Application implements EmbeddedServletContainerCustomizer,EnvironmentAware {
	
	private final static int DEFAULT_PORT=8080;
	
	private static String args[];
	
	private Environment environment;

	private int port=DEFAULT_PORT;

	public static void main(String args[]) throws Exception {
		new Application(args);
	}
	
	public Application() {
		
	}
	
	public Application(String args[]) {
		this.args=args;
		SpringApplication.run(Application.class, args);
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.environment=environment;
	}
	
	@Override
	public void customize(ConfigurableEmbeddedServletContainer container) {
		initConfig();

		container.addErrorPages(new ErrorPage("/app/index.html"));
		container.setPort(this.port);
	}
	
	protected void initConfig() {
		String port=environment.getProperty("port");
		if(!StringUtils.isNumeric(port)) {
			return;
		}
		
		this.port=Integer.parseInt(port);
	}

	public void setPort(int port) {
		this.port = port;
	}
	public int getPort() {
		return port;
	}
}